package com.woyao;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.squareup.picasso.Picasso;
import com.woyao.core.FileUtil;
import com.woyao.core.model.ProfileResponse;
import com.woyao.core.model.User;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.FileNotFoundException;
import java.io.IOException;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

//import com.woyao.core.AreaPopUp;

public class VerifyActivity extends AppCompatActivity {
    private User user = new User();

    ProgressDialog progressDialog;
    private ImageView  idcard;
    private ImageView cert;
    private ImageView buzzcard;
    private  TextView memo;

    Integer IDCARD_CODE = 100;
    Integer BUZZCARD_CODE =  200;
    Integer CERT_CODE =  300;

    private  Integer theCode = 0 ;

    private ProgressBar progress;
    private static final   int PERMISSION_REQUEST_STORAGE = 1;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        progress = (ProgressBar)  findViewById(R.id.account_uploading);




        final Button nextbtn = (Button) findViewById(R.id.add_next);

        nextbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });

        memo = (TextView)findViewById(R.id.verify_memo);

        idcard = (ImageView)findViewById(R.id.id_idcard);

        idcard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                theCode = IDCARD_CODE;
                checkPerm( );


            }
        });

        buzzcard = (ImageView)findViewById(R.id.id_buzzcard);

        buzzcard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                theCode = BUZZCARD_CODE;
                checkPerm( );

            }
        });

        cert = (ImageView) findViewById(R.id.orgedit_cert);
        cert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                theCode = CERT_CODE;
                checkPerm( );
            }
        });

        this.setTitle("请完成认证");
        loadData();



    }

    private void checkPerm( ) {
        /**1.在AndroidManifest文件中添加需要的权限。
         *
         * 2.检查权限
         *这里涉及到一个API，ContextCompat.checkSelfPermission，
         * 主要用于检测某个权限是否已经被授予，方法返回值为PackageManager.PERMISSION_DENIED
         * 或者PackageManager.PERMISSION_GRANTED。当返回DENIED就需要进行申请授权了。
         * */
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){ //权限没有被授予

            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("信息").
                    setMessage( "为上传图片，请授权访问设备的图片资料").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(VerifyActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    520);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).create();
            alertDialog.show();
        }else{//权限被授予
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/");
            // start the image capture Intent
            startActivityForResult(intent, theCode);
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == 520)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/");
                // start the image capture Intent
                startActivityForResult(intent, theCode);
            } else
            {
                Toast.makeText(VerifyActivity.this, "权限被拒绝，图片不能正常上传", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        finish();
        return true;
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         if (requestCode == IDCARD_CODE && resultCode == RESULT_OK) {
             String localpicpath = "";
            try{
                Uri selectedImage = data.getData();

                Bitmap preview =null;
                try {
                    preview = FileUtil.decodeUri(selectedImage, VerifyActivity.this);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                localpicpath = Common.getPath(VerifyActivity.this,selectedImage);

//                String[] filePathColumn = {MediaStore.Images.Media.DATA};
//
//                Cursor cursor = getContentResolver().query(
//                        selectedImage, filePathColumn, null, null, null);
//                if(cursor!=null) {
//                    cursor.moveToFirst();
//                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                    localpicpath = cursor.getString(columnIndex);
//                    cursor.close();
//                }
//                else
//                {
//                    localpicpath = selectedImage.getPath();
//                }

                uploadIDcard(  localpicpath,preview );

            }catch(Exception e){
                e.printStackTrace();
                Common.reportError(userId,"storage","verify","idcard access", localpicpath +"###" + e.getMessage());
            }
        }else if(requestCode == BUZZCARD_CODE &&resultCode==RESULT_OK) {
             String localpicpath = "";
             try {
                 Uri selectedImage = data.getData();

                 Bitmap preview = null;
                 try {
                     preview = FileUtil.decodeUri(selectedImage, VerifyActivity.this);
                 } catch (FileNotFoundException e) {
                     e.printStackTrace();
                 }
                 localpicpath = Common.getPath(VerifyActivity.this, selectedImage);

                 uploadBUZZcard(localpicpath, preview);

             } catch (Exception e) {
                 e.printStackTrace();
                 Common.reportError(userId,"storage","verify","buzzcard access", localpicpath +"###" + e.getMessage());
             }
         }else if(requestCode == CERT_CODE &&resultCode==RESULT_OK){
             String localpicpath = "";
             try {
                 Uri selectedImage = data.getData();

                 Bitmap preview = null;
                 try {
                     preview = FileUtil.decodeUri(selectedImage, VerifyActivity.this);
                 } catch (FileNotFoundException e) {
                     e.printStackTrace();
                 }
                 localpicpath = Common.getPath(VerifyActivity.this,selectedImage);
//                 String picturePath;
//                 String[] filePathColumn = {MediaStore.Images.Media.DATA};
//                 Cursor cursor = getContentResolver().query(
//                         selectedImage, filePathColumn, null, null, null);
//                 if(cursor!=null) {
//                     cursor.moveToFirst();
//                     int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                     picturePath = cursor.getString(columnIndex);
//                     cursor.close();
//                 }
//                 else
//                 {
//                     picturePath = selectedImage.getPath();
//                 }

                 uploadCert(localpicpath,preview);

             }catch(Exception e){
                 e.printStackTrace();
                 Common.reportError(userId,"storage","verify","cert access", localpicpath +"###" + e.getMessage());
             }
         }
    }



    public void showFailure() {//自定义方法名tt
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progress.setVisibility(View.GONE);
                progressDialog.dismiss();
                Common.showSnack(VerifyActivity.this,cert,"上传失败");
            }
        });
    }

    public void showIdcard(final Bitmap preview) {//自定义方法名tt
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progress.setVisibility(View.GONE);
                progressDialog.dismiss();
                idcard.setImageBitmap(preview);
                Common.showSnack(VerifyActivity.this,cert,"上传成功");
            }
        });
    }

    public void showBuzzcard(final Bitmap preview) {//自定义方法名tt
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progress.setVisibility(View.GONE);
                progressDialog.dismiss();
                buzzcard.setImageBitmap(preview);
                Common.showSnack(VerifyActivity.this,cert,"上传成功");
            }
        });
    }

    public void showCert(final Bitmap preview) {//自定义方法名tt
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progress.setVisibility(View.GONE);
                progressDialog.dismiss();
                cert.setImageBitmap(preview);
                Common.showSnack(VerifyActivity.this,cert,"上传成功");
            }
        });
    }
    private void uploadIDcard( final String localpicpath,final Bitmap preview ){
        progressDialog = new ProgressDialog(VerifyActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("图片上传中...");
        progressDialog.show();

        final String filename =  FileUtil.getIDcardObjectKey();
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, localpicpath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                progress.setVisibility(View.VISIBLE);
                progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                showIdcard(preview);
                Common.setProfileAttr("idcard", "aliyun"+ filename);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                showFailure();
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    Common.reportError(userId,"upload","verify","idcardupload", localpicpath +"###" + clientExcepion.getMessage());
                }
                if (serviceException != null) {
                    // 服务异常
                    Common.reportError(userId,"upload","verify","idcardupload", localpicpath +"###" + serviceException.getMessage());
                }
            }
        });

    }
    private void uploadCert( final String picturePath,final Bitmap preview){

        progressDialog = new ProgressDialog(VerifyActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("图片上传中...");
        progressDialog.show();
        final String filename = FileUtil.getCertObjectKey();
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, picturePath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                progress.setVisibility(View.VISIBLE);
                progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                showCert(preview);
                Common.setProfileAttr("cert", "aliyun"+ filename);
                Common.showSnack(VerifyActivity.this, cert, "上传成功" );
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                showFailure();
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    Common.reportError(userId,"upload","verify","certupload", picturePath +"###" + clientExcepion.getMessage());
                }
                if (serviceException != null) {
                    // 服务异常
                    Common.reportError(userId,"upload","verify","certupload", picturePath +"###" + serviceException.getMessage());
                }
            }
        });

    }
    private void uploadBUZZcard( final String localpicpath,final Bitmap preview ){
        progressDialog = new ProgressDialog(VerifyActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("图片上传中...");
        progressDialog.show();

        final String filename =  FileUtil.getBUZZcardObjectKey();
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, localpicpath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                progress.setVisibility(View.VISIBLE);
                progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                showBuzzcard(preview);
                Common.setProfileAttr("buzzcard", "aliyun"+ filename);
                Common.showSnack(VerifyActivity.this, cert, "上传成功" );
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                showFailure();
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    Common.reportError(userId,"upload","verify","buzzcardupload", localpicpath +"###" + clientExcepion.getMessage());
                }
                if (serviceException != null) {
                    // 服务异常
                    Common.reportError(userId,"upload","verify","buzzcardupload", localpicpath +"###" + serviceException.getMessage());
                }
            }
        });

    }

    private void loadData(){

        AsyncTask<Void,Void,ProfileResponse> loadTask =
                new AsyncTask<Void, Void, ProfileResponse>() {
                    @Override
                    protected ProfileResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<ProfileResponse> responseCall = svc.getProfile(userId,"android","");
                        try {
                            ProfileResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                    @Override
                    protected void onPostExecute(final ProfileResponse response) {
                        if(response != null && response.isSuccess()){
                            render(response);
                        }
                    }
                };
        loadTask.execute((Void)null);
    }



    private void render(ProfileResponse response){
        this.user = response.getContent();

        if (StringUtil.notNullOrEmpty(user.getCert())) {
            Picasso.with(this)
                    .load(user.getCert())
                    .into(cert);
        }

        String idcardstr = user.getIdcard();
        if (StringUtil.notNullOrEmpty(idcardstr)) {

            Picasso.with(this)
                    .load(idcardstr)
                    .into(idcard);
        }

        String buzzcardstr = user.getBuzzcard();
        if (StringUtil.notNullOrEmpty(buzzcardstr)) {

            Picasso.with(this)
                    .load(buzzcardstr)
                    .into(buzzcard);
        }

        if (!user.getMemo().equals("")){
            memo.setText(user.getMemo());
        }


    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
